<template>
  <div ref="chart" class="chart" :style="style"></div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, getCurrentInstance, toRefs, toRaw } from "vue";

// 接收值
const props = defineProps({
  option: {
    type: Object,
    default: () => {},
  },
});

// 定义值
const chart = ref();
const style = reactive({
  width: "100%",
  height: "420px",
  background: "#f8f8f8",
  borderRadius: "8px",
});

const instance = getCurrentInstance();
const echarts = instance?.appContext.config.globalProperties.$echarts;

const optionList = reactive({
  title: {
    text: "",
  },
  color: ["#27C1FF", "#F1A821"],
  backgroundColor: "#FFFFFF",
  tooltip: {
    trigger: "axis",
  },
  legend: {
    show: true,
    left: "right",
    data: ["出库", "入库"],
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    data: [],
  },
  yAxis: {
    type: "value",
    name: "入库数量",
  },
  series: [
    {
      name: "出库",
      type: "line",
      data: [],
    },
    {
      name: "入库",
      type: "line",
      data: [],
    },
  ],
});

// 定义加载函数
const initCharts = () => {
  let myChart = echarts.init(chart.value);
  myChart.setOption(optionList);
  window.addEventListener("resize", () => {
    myChart.resize();
  });
};

// 监听当配置项发生变化的时候，调用加载函数
watch(
  () => props.option,
  (val) => {
    nextTick(() => {
      const datum = toRaw(val);
      optionList.xAxis.data = datum?.day;
      optionList.series[0].data = datum?.out_num;
      optionList.series[1].data = datum?.in_num;
      initCharts();
    });
  },
  { immediate: true }
);

onMounted(() => {
  initCharts();
});
</script>

<style lang="less" scoped></style>
